package com.studyjava.guessdx;

import static java.lang.System.exit;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.util.Xml;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.media.MediaPlayer;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlSerializer;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

public class choose_pic_time extends AppCompatActivity {

    private TextView textViewIdStr;
    private GridLayout imageGrid;
    private int correctId;
    private String correctStr;
    private String correctFileName;
    private int correctClickCount;  // 记录正确点击次数
    private TextView timerTextView;  // 显示计时器的文本框
    private CountDownTimer timer;  // 计时器对象
    private long timeRemaining = 60000;  // 剩余时间，初始60秒
    private int userScore;  // 用户积分
    private TextView scoreTextView;  // 显示积分的文本框
    private Button skipButton;
    private MediaPlayer mediaPlayer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.choose_pic_time);

        textViewIdStr = findViewById(R.id.textView);
        timerTextView = findViewById(R.id.timerTextView);
        scoreTextView = findViewById(R.id.scoreTextView);  // 显示积分的文本框
        skipButton = findViewById(R.id.skipButton);
        imageGrid = findViewById(R.id.gridLayout);

        loadUserScore();  // 加载用户积分

        correctClickCount = 0;  // 初始化正确点击次数

        // 设置跳过按钮点击事件
        skipButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadAndDisplayImages();
            }
        });

        // 确保布局加载完成后再设置子项大小
        ViewTreeObserver viewTreeObserver = imageGrid.getViewTreeObserver();
        if (viewTreeObserver.isAlive()) {
            viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    imageGrid.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    startTimer();  // 启动计时器
                    loadAndDisplayImages();
                }
            });
        }

        // 初始化背景音乐播放器
        mediaPlayer = MediaPlayer.create(this, R.raw.time_bg);  // 播放 assets/time_bg.wav
        mediaPlayer.setLooping(true);  // 设置循环播放
        mediaPlayer.start();  // 开始播放
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 释放 MediaPlayer 资源
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

    private void startTimer() {
        timer = new CountDownTimer(timeRemaining, 1000) {  // 每隔1秒更新一次
            @Override
            public void onTick(long millisUntilFinished) {
                timeRemaining = millisUntilFinished;
                timerTextView.setText("剩余时间: " + timeRemaining / 1000 + "秒");
            }

            @Override
            public void onFinish() {
                timerTextView.setText("时间到！");
                showResultDialog();
            }
        }.start();
    }

    // 展示结果对话框
    private void showResultDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(choose_pic_time.this);
        builder.setTitle("时间到！");
        builder.setMessage("你点击了 " + correctClickCount + " 次正确的图片。\n当前积分: " + userScore + " (+" + correctClickCount * 0.2 + " )");

        // 返回菜单按钮
        builder.setPositiveButton("返回菜单", (dialog, which) -> {
            int earnedPoints = (int) (correctClickCount * 0.2);
            userScore += earnedPoints;  // 将正确次数乘以0.2作为积分
            saveUserScore();  // 保存积分
            dialog.dismiss();
            finish();  // 结束游戏，返回菜单
        });

        // 再来一局按钮
        builder.setNegativeButton("再来一局", (dialog, which) -> {
            int earnedPoints = (int) (correctClickCount * 0.2);
            userScore += earnedPoints;  // 将正确次数乘以0.2作为积分
            saveUserScore();  // 保存积分
            dialog.dismiss();
            resetGame();  // 重置游戏，重新开始
        });

        builder.setCancelable(false);  // 对话框不可取消
        builder.show();
    }


    private void resetGame() {
        correctClickCount = 0;
        timeRemaining = 60000;  // 重置为60秒
        startTimer();  // 重新开始计时器
        loadAndDisplayImages();  // 重新加载图片
    }

    private void loadAndDisplayImages() {
        parseXMLAndSetTextView();  // 设置显示文本

        imageGrid.removeAllViews();  // 清除之前的图片视图

        List<String> imageFiles = new ArrayList<>();
        try {
            // 获取 assets/music_pic 目录下的所有文件
            String[] files = getAssets().list("music_pic");
            for (String file : files) {
                if (file.startsWith("UI_Jacket_")) {
                    imageFiles.add(file);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 移除正确答案的文件，并打乱文件列表顺序
        imageFiles.remove(correctFileName);
        Collections.shuffle(imageFiles);

        // 随机放置正确答案
        int correctImagePosition = (int) (Math.random() * 9);
        imageFiles.add(correctImagePosition, correctFileName);

        // 获取 gridLayout 的宽度
        int gridWidth = imageGrid.getWidth();
        int imageSize = gridWidth / 3;  // 计算每张图片的大小

        // 创建 9 个 ImageView，并加载图片
        for (int i = 0; i < 9; i++) {
            final String imageName = imageFiles.get(i);
            ImageView imageView = new ImageView(this);

            // 设置布局参数
            GridLayout.LayoutParams layoutParams = new GridLayout.LayoutParams();
            layoutParams.width = imageSize;
            layoutParams.height = imageSize;
            layoutParams.setMargins(0, 0, 0, 0);  // 无边距
            imageView.setLayoutParams(layoutParams);

            // 从 assets 加载图片
            Bitmap bitmap = loadImageFromAssets("music_pic/" + imageName);
            if (bitmap != null) {
                imageView.setImageBitmap(bitmap);
            } else {
                imageView.setBackgroundColor(0xFFCCCCCC);  // 如果图片加载失败，显示灰色背景
            }

            // 设置点击事件
            imageView.setOnClickListener(v -> {
                if (imageName.equals(correctFileName)) {
                    correctClickCount++;
                    timeRemaining += 3000;  // 答对加3秒
                    timer.cancel();  // 重新启动计时器
                    startTimer();
                    loadAndDisplayImages();  // 加载新问题
                } else {
                    timeRemaining -= 1000;  // 答错扣1秒
                    timer.cancel();
                    startTimer();
                    Toast.makeText(choose_pic_time.this, "错误，请再试一次！", Toast.LENGTH_SHORT).show();
                }
            });

            imageGrid.addView(imageView);
        }
    }


    private void parseXMLAndSetTextView() {
        try {
            InputStream inputStream = getAssets().open("MusicSort.xml");
            XmlPullParser xpp = Xml.newPullParser();
            xpp.setInput(inputStream, null);

            List<Integer> ids = new ArrayList<>();
            List<String> strs = new ArrayList<>();
            int eventType = xpp.getEventType();
            while (eventType != XmlPullParser.END_DOCUMENT) {
                String tag = xpp.getName();
                if (eventType == XmlPullParser.START_TAG && "id".equals(tag)) {
                    ids.add(Integer.parseInt(xpp.nextText()));
                } else if (eventType == XmlPullParser.START_TAG && "str".equals(tag)) {
                    strs.add(xpp.nextText());
                }
                eventType = xpp.next();
            }
            inputStream.close();

            Random random = new Random();
            int randomIndex = random.nextInt(ids.size());
            correctId = ids.get(randomIndex);
            correctStr = strs.get(randomIndex);

            textViewIdStr.setText("ID: " + correctId + "\nStr: " + correctStr);

            correctFileName = String.format("UI_Jacket_%06d.png", correctId > 9999 ? correctId - 10000 : correctId);
        } catch (IOException | XmlPullParserException e) {
            e.printStackTrace();
        }
    }

    private Bitmap loadImageFromAssets(String fileName) {
        try {
            // 打开assets中的文件
            InputStream is = getAssets().open(fileName);

            // 设置解码选项，确保图片加载
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = false;  // 加载完整图片

            Bitmap bitmap = BitmapFactory.decodeStream(is, null, options);
            is.close();

            if (bitmap == null) {
                // 如果解码失败，返回null
                throw new IOException("无法解码图片: " + fileName);
            }

            return bitmap;
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this, "图片加载失败: " + fileName, Toast.LENGTH_SHORT).show();
            return null;
        }
    }


    private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            inSampleSize = Math.min(heightRatio, widthRatio);
        }

        return inSampleSize;
    }

    // 从文件中加载用户积分
    // 从文件中加载用户积分
    private void loadUserScore() {
        try {
            InputStream inputStream = openFileInput("userdata.xml");
            XmlPullParser parser = Xml.newPullParser();
            parser.setInput(inputStream, "UTF-8");

            int eventType = parser.getEventType();
            while (eventType != XmlPullParser.END_DOCUMENT) {
                String tagName = parser.getName();
                if (eventType == XmlPullParser.START_TAG && "Score".equals(tagName)) {  // 确保标签与保存时一致
                    userScore = Integer.parseInt(parser.nextText());
                }
                eventType = parser.next();
            }
            inputStream.close();
            updateScoreDisplay();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void updateScoreDisplay() {
        scoreTextView.setText("当前积分: " + userScore);
    }


    private void saveUserScore() {
        FileOutputStream fos = null;
        try {
            // 打开文件进行保存
            fos = openFileOutput("userdata.xml", MODE_PRIVATE);
            XmlSerializer serializer = Xml.newSerializer();
            serializer.setOutput(fos, "UTF-8");

            // 开始构建 XML 数据
            serializer.startDocument(null, true);
            serializer.startTag(null, "userdata");

            // 保存积分
            serializer.startTag(null, "Score");  // 使用和读取时一致的标签"Score"
            serializer.text(String.valueOf(userScore));
            serializer.endTag(null, "Score");

            // 结束 XML 构建
            serializer.endTag(null, "userdata");
            serializer.endDocument();
            fos.close();

            // 更新UI显示积分
            scoreTextView.setText("积分: " + userScore);
            Toast.makeText(this, "积分已保存", Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this, "保存用户数据失败", Toast.LENGTH_SHORT).show();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


}
